package com.kikikeji.weizhuo.activity.core;

import android.app.Activity;

import com.kikikeji.weizhuo.util.DebugLog;

import java.lang.ref.WeakReference;
import java.util.Stack;

public class ActivityStack extends Stack<WeakReference<Activity>> {

    private static final java.lang.String TAG = "ActivityStack";

    public void addActivity(Activity activity) {
        WeakReference<Activity> innerActivity = new WeakReference<Activity>(activity);
        push(innerActivity);
    }

    public void removeActivity(Activity activity) {
        WeakReference<Activity> innerActivity = new WeakReference<Activity>(activity);
        if (isEmpty()) {
            return;
        }

        for (int i=0; i<size(); i++) {
            if (isSameActivity(activity, get(i).get())) {
                remove(i);
            }
        }
    }

    private boolean isSameActivity(Activity activity1, Activity activity2) {
        return activity1.equals(activity2);
    }


    /**
     * 清理栈
     */
    @Override
    public void clear() {
        WeakReference<Activity> activity;

        DebugLog.w(TAG, "clearActivityStack, -->" + size());
        while(!isEmpty()) {
            activity = pop();
            destroyActivity(activity);
        }
    }

    private void destroyActivity(WeakReference<Activity> activity) {
        if (null != activity && null != activity.get() && !activity.get().isFinishing()) {
            activity.get().finish();
            DebugLog.w(TAG, "finish Activity:" + activity.get());
        }
    }
}
